﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using br.com.portocs.unidaacademico.framework;

namespace br.com.portocs.unidaacademico.repositorio.conventions
{
    public class TableName
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EndingFirstName
        {
            get { return FirstName.Substring(FirstName.Length - 2); }
        }

        public string FirstNameWithoutEnding
        {
            get { return FirstName.Substring(0, FirstName.Length - 2); }
        }
        public bool NeedPluralization
        {
            get { return CompleteName.Length > 2; }
        }
        public string CompleteName
        {
            get
            {
                return IsCompoundName
                           ? string.Format("{0}_{1}", FirstName.ToLower(), LastName.ToLower())
                           : FirstName.ToLower();
            }
        }

        public bool IsCompoundName
        {
            get { return !LastName.Equals(string.Empty); }
        }

        public void ReplaceEnding(string newEnding)
        {
            FirstName = FirstNameWithoutEnding + newEnding;
        }

        private static int GetIndexFirstOccurrence(string name)
        {
            var indice = 0;

            //  Identifica se é palavra composta
            for (int i = 1; i < name.Length; i++)
            {
                if (char.IsUpper(name[i]))
                {
                    indice = i;
                    break;
                }
            }

            return indice;
        }

        public string GetCompleteName(string name)
        {
            var indice = GetIndexFirstOccurrence(name);

            if (!indice.Equals(0))
            {
                FirstName = name.Substring(0, indice);
                LastName = name.Substring(indice);
            }
            else
                FirstName = name;

            if (NeedPluralization)
            {
                FirstName =
                    FirstName.PluralizePortugueseBrazilian();
            }

            return CompleteName;
        }

        public TableName()
        {
            LastName = string.Empty;
        }
    }
}